import { useState, useEffect, useCallback } from 'react'
import { formatDate } from '../util/tools.js'
import styles from '../css/IssueItem.module.css'
import { Tag } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { getUserById } from '../api/user'
import { getListAsync } from '../redux/typeSlice'
import { useNavigate } from 'react-router-dom'

export default function IssueItem(props) {
  const colorArr = ['#108ee9', '#2db7f5', '#f50', 'green', '#87d068', 'blue', 'red', 'purple']
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const [userInfo, setUserInfo] = useState({}) // 存储用户的信息
  const { typeList } = useSelector((state) => state.type)
  const getLsit = useCallback(async () => {
    const res = await getUserById(props.issueInfo.userId)
    setUserInfo(res.data)
  }, [props.issueInfo.userId])
  // 获取typeList的数据
  useEffect(() => {
    if (!typeList.length) {
    dispatch(getListAsync())
    }
    getLsit()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [getLsit])
  const type = typeList.find((item) => item._id === props.issueInfo.typeId)
  return (
    <div className={styles.container}>
      {/* 回答数 */}
      <div className={styles.issueNum}>
        <div>{props.issueInfo.commentNumber}</div>
        <div>回答</div>
      </div>
      {/* 浏览数 */}
      <div className={styles.issueNum}>
        <div>{props.issueInfo.scanNumber}</div>
        <div>浏览</div>
      </div>
      {/* 问题内容 */}
      <div className={styles.issueContainer}>
        <div onClick={() => navigate(`/issues/${props.issueInfo._id}`)} className={styles.top}>
          {props.issueInfo.issueTitle}
        </div>
        <div className={styles.bottom}>
          <div className={styles.left}>
            <Tag color={colorArr[typeList.indexOf(type) % colorArr.length]}>{type?.typeName}</Tag>
          </div>
          <div className={styles.right}>
            <Tag color="volcano">{userInfo.nickname}</Tag>
            <span>{formatDate(props.issueInfo.issueDate, 'year')}</span>
          </div>
        </div>
      </div>
    </div>
  )
}
